package com.mf.morefun.ui.gifts;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.adapter.GiftAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.ExchangeBean;
import com.mf.morefun.bean.GiftBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.UserInfoBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.ReadDetailTypeListener;
import com.mf.morefun.requestbean.RequesBannerBean;
import com.mf.morefun.requestbean.RequestExchangeBean;
import com.mf.morefun.requestbean.RequestUserBean;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.ui.personnelmanagement.PersonnelManagementActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GiftsListActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.iv_idea)
    ImageView ivIdea;
    @BindView(R.id.gvv_gift)
    GridView gvvGift;
    private List<GiftBean> mGiftList = new ArrayList<>();
    private SPUtils mSputils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_giftslist;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSputils = new SPUtils(getApplicationContext());
        if (!IsLoginBean.isNo(false)){
            GetUserInfo.initLogin(mSputils.getString(Configuration.USERPHONE), mSputils.getString(Configuration.USERPASSWORD));
        }
        tvNum.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getEnergyStones() + "");
        if (null != MoreFunApplication.loginBean.getResult().getOrgan()){
            initGetGiftsList();
        }
        initGetUser(mSputils.getString(Configuration.USERID));
    }

    private void initGetUser(String userId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.USERINFO);
        RequestUserBean userBean = new RequestUserBean();
        userBean.setId(userId);
        params.setBodyContent(JSON.toJSONString(userBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(mResult.getResult())){
                            UserInfoBean user = JSON.parseObject(mResult.getResult(), UserInfoBean.class);
                            if (null != user.getUserFinance()){
                                tvNum.setText(user.getUserFinance().getEnergyStones() + "");
                            }
                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initExchangeGift(String id, int costEnegyStone) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.EXCHANGEGIFT);
        RequestExchangeBean requestExchangeBean = new RequestExchangeBean();
        RequestExchangeBean.PrizeBean prizeBean = new RequestExchangeBean.PrizeBean();
        prizeBean.setId(id);
        RequestExchangeBean.UserBean userBean = new RequestExchangeBean.UserBean();
        userBean.setId(mSputils.getString(Configuration.USERID));
        requestExchangeBean.setPrize(prizeBean);
        requestExchangeBean.setUser(userBean);
        params.setBodyContent(JSON.toJSONString(requestExchangeBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0){
                        MoreFunApplication.loginBean.getResult().getUserFinance().setEnergyStones(MoreFunApplication.loginBean.getResult().getUserFinance().getEnergyStones() - costEnegyStone);
                        tvNum.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getEnergyStones() + "");
                        showResponseDialog(true, "");
                    }else {
                        showResponseDialog(false, resultBean.getMessage());
                    }
                }else {
                    showResponseDialog(false, "兑换失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(GiftsListActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    private void showResponseDialog(boolean isSuccess, String message) {
        final Dialog dialog = new Dialog(GiftsListActivity.this, R.style.loginerrordialog);
        View view = LayoutInflater.from(GiftsListActivity.this).inflate(R.layout.layout_responsedialog, null);
        dialog.setContentView(view);
        ImageView iv_image = view.findViewById(R.id.iv_image);
        TextView tv_type = view.findViewById(R.id.tv_type);
        TextView tv_typeinfo = view.findViewById(R.id.tv_typeinfo);
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        TextView tv_con = view.findViewById(R.id.tv_con);
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        LinearLayout ll_bg = view.findViewById(R.id.ll_bg);
        ImageView iv_close = view.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        if (isSuccess){//成功
            iv_image.setImageResource(R.mipmap.gift_exchange_succes);
            tv_con.setVisibility(View.VISIBLE);
            tv_type.setText("你已成功兑换该商品。");
            tv_typeinfo.setVisibility(View.VISIBLE);
            tv_typeinfo.setText("可前往我的成就查看物流信息。");
            tv_sure.setText("查看");
            ll_bg.setBackgroundResource(R.mipmap.giftsuccess);
        }else {
            tv_con.setVisibility(View.GONE);
            ll_bg.setBackgroundResource(R.mipmap.giftfail);
            tv_sure.setText("确定");
            tv_type.setText(message);
            tv_typeinfo.setVisibility(View.GONE);
            iv_image.setImageResource(R.mipmap.gift_exchange_fail);
        }
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (DeviceUtils.deviceWidth(mContext) * 0.4);
        lp.height = (int) (DeviceUtils.deviceWidth(mContext) * 0.4);
        dialogWindow.setAttributes(lp);
    }
    private void initGetGiftsList() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GIFTLIST);
        RequesBannerBean bannerBean = new RequesBannerBean();
        RequesBannerBean.OrganBean organBean = new RequesBannerBean.OrganBean();
        organBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        bannerBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(bannerBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mGiftList.clear();
                if (!StringUtils.isEmpty(result)){
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(resultBean.getResult())){
                            List<GiftBean> giftList = JSON.parseArray(resultBean.getResult(), GiftBean.class);
                            mGiftList.addAll(giftList);
                            GiftAdapter adapter = new GiftAdapter(GiftsListActivity.this, mGiftList);
                            gvvGift.setAdapter(adapter);
                            adapter.setListener(new ReadDetailTypeListener() {
                                @Override
                                public void callBack(int position) {
                                    //兑换礼物
                                    if (null != mGiftList && mGiftList.size() > 0){
                                        //先弹出个确定窗口
                                        showSelectDialog(mGiftList, position);
                                    }
                                }
                            });
                        }else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void showSelectDialog(List<GiftBean> mGiftList, int position) {
        final Dialog dialogs = new Dialog(GiftsListActivity.this, R.style.loginerrordialog);
        View view = LayoutInflater.from(GiftsListActivity.this).inflate(R.layout.layout_selectdialog, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogs.dismiss();
            }
        });
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogs.dismiss();
                initExchangeGift(mGiftList.get(position).getId(), mGiftList.get(position).getCostEnegyStone());
            }
        });
        dialogs.setContentView(view);
        dialogs.setCancelable(false);
        dialogs.setCanceledOnTouchOutside(false);
        dialogs.show();
        Window dialogWindow = dialogs.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (DeviceUtils.deviceWidth(mContext) * 0.4);
        lp.height = (int) (DeviceUtils.deviceWidth(mContext) * 0.4);
        dialogWindow.setAttributes(lp);
    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.iv_back, R.id.iv_idea})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_idea:
                Intent mIntent = new Intent(GiftsListActivity.this, GiftIdeaActivity.class);
                startActivity(mIntent);
                break;
        }
    }
}
